import { StyleSheet, Text, View, ScrollView, Image, ImageBackground, Pressable, RefreshControl } from 'react-native';
import FastImage from '@d11/react-native-fast-image';
import React, { useState, useEffect, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useNavigation, useIsFocused } from '@react-navigation/native';
import { useCameraPermission } from 'react-native-vision-camera';
import { NordicDFU } from 'react-native-nordic-dfu';
import RNFS from 'react-native-fs2';
import Icon from 'react-native-vector-icons/Ionicons';
import dayjs from 'dayjs';
import { useBlockBackHandler, useBindDeviceList, useDeviceType } from '~/common';
import { FocusAwareStatusBar, DfuProGressModal } from '~/components';
import { deviceStore, observer, userStore } from '~/store';
import {
    checkAndRequestLocationPermissions,
    checkAndRequestBluetoothPermissions,
    checkAndRequestLocationAndBluetoothPermissions,
} from '~/utils/permission';
import { isIos, px2dp, scale, width } from '~/utils/px2dp';
import BleConnection from '~/utils/ble/connect';
import { yjhDevices, offlineCourseDevices } from '~/utils/deviceMenues';
import { getDeviceNewFirmwareCode, checkVersion, getDeviceUploadUrl } from '~/api/deviceApi';
import { getDeviceDataHead } from '~/utils/ble/getBleData';
import SelectCalendar from './components/SelectCalendar';
import DeviceData from './components/DeviceData';
import ConnectDeviceModal from './components/ConnectDeviceModal';
import SelectDeviceModal from './components/SelectDeviceModal';

const Bleconnect = BleConnection.getInstance();
export default observer(() => {
    const isFocused = useIsFocused();
    useBlockBackHandler();
    useBindDeviceList();
    useDeviceType();
    const navigation: any = useNavigation();
    const { t } = useTranslation();
    const insets = useSafeAreaInsets();
    const { device, connectDeviceInfo } = deviceStore;
    const { userBindDeviceData, autoConnectDeviceSn } = userStore;
    const deviceInfo = useMemo(() => {
        let res = userBindDeviceData.find((item) => item.device_sn == autoConnectDeviceSn);
        if (deviceStore.device?.connectedDeviceStatus == 1) {
            res = userBindDeviceData.find((item) => item.device_sn == device?.connectDevice?.device_sn);
        } else {
            if (autoConnectDeviceSn) {
                res = userBindDeviceData.find((item) => item.device_sn == autoConnectDeviceSn);
            } else {
                res = userBindDeviceData[0];
            }
        }
        return res;
    }, [
        userBindDeviceData,
        autoConnectDeviceSn,
        deviceStore.device?.connectedDeviceStatus,
        device?.connectDevice?.device_sn,
    ]);
    // 日历查看
    const [visible, setVisible] = useState(false);
    const [currentDate, setCurrentDate] = useState(dayjs().format('YYYY-MM-DD'));
    const handlePrevDay = () => {
        setCurrentDate((prev) => dayjs(prev).subtract(1, 'day').format('YYYY-MM-DD'));
    };
    const handleNextDay = () => {
        setCurrentDate((prev) => dayjs(prev).add(1, 'day').format('YYYY-MM-DD'));
    };
    const getDisplayText = () => {
        const date = dayjs(currentDate);
        if (date.isSame(dayjs(), 'day')) {
            return t('HomeScreen.t8');
        }
        return date.format('MM-DD');
    };
    const onSelectDate = (res) => {
        setCurrentDate(res);
    };

    // 连接设备
    const checkPermissions = async (): Promise<boolean> => {
        const hasLocationPermissions = await checkAndRequestLocationPermissions();
        const hasBluetoothPermissions = await checkAndRequestBluetoothPermissions();
        if (!hasLocationPermissions && hasBluetoothPermissions) {
            Toast.show({ content: t('HomeScreen.t9'), layout: 'top' });
            return false;
        }
        return true;
    };
    // 添加设备
    const { hasPermission, requestPermission } = useCameraPermission();
    const addDevice = () => {
        if (hasPermission) {
            navigation.navigate('ScanBleDevice');
        } else {
            requestPermission();
        }
    };
    // 连接设备
    const [ConnectVisible, setConnectVisible] = useState(false);
    const connectDevice = async () => {
        if (userStore.userBindDeviceData.length == 0) {
            addDevice();
            return;
        }
        const { connectDevice, connectedDeviceStatus, deviceStatus } = deviceStore.device;
        if (connectedDeviceStatus == 1) {
            // 假如设备已经连接
            if (yjhDevices.indexOf(connectDevice.device_code) !== -1) {
                navigation.navigate('AcupoinDeviceDetailes', { device_sn: connectDevice.device_sn });
            } else {
                navigation.navigate('DeviceDetailes');
            }
        } else {
            const permissionsGranted = await checkPermissions();
            if (!permissionsGranted) return;
            if (deviceStatus == 0) {
                Toast.show({ content: t('HomeScreen.t10'), layout: 'top' });
                return;
            }
            Bleconnect.scan(5);
            if (userStore.userBindDeviceData.length > 1) {
                setSwitchDeviceVisible(true);
            } else {
                if (userStore.autoConnectDeviceSn) {
                    setConnectVisible(true);
                } else {
                    setSwitchDeviceVisible(true);
                }
            }
        }
    };

    // 空中升级失败----补偿升级
    const [updateVisible, setUpdateVisible] = useState(false);
    const isNewDevice = (version) => {
        const dotCount = (version.match(/\./g) || []).length;
        return dotCount === 3;
    };

    const updateDevice = async () => {
        const { device_sn, device_code, id } = deviceStore.dfuDevice;
        const versionInfo = await getDeviceNewFirmwareCode({ device_sn });
        const firmWareVersion = 'V' + versionInfo.msg;
        let obj = {
            firmware_code: device_code,
            version_sn: firmWareVersion,
            device_sn: device_sn,
        };
        const res = await checkVersion(obj);
        if (res.status == 2) {
            Toast.show({ content: firmWareVersion + t('HomeScreen.t11') });
            setUpdateVisible(false);
            return;
        }

        if (parseInt(res.status) === 1) {
            getDeviceUploadUrl({
                firmware_code: res.data.firmware_code,
                version_sn: res.data.version_sn,
            })
                .then(async (result) => {
                    if (result.status == 1) {
                        const localZipPath = `${RNFS.DocumentDirectoryPath}/device.zip`;
                        let url = isNewDevice(firmWareVersion) ? result.data.new_url : result.data.url;
                        const downloadFileRes = await RNFS.downloadFile({
                            fromUrl: url,
                            toFile: localZipPath,
                        }).promise;
                        if (downloadFileRes.statusCode !== 200) {
                            return;
                        }
                        const dfuFilePath = isIos() ? `file://${localZipPath}` : localZipPath;
                        NordicDFU.startDFU({
                            deviceAddress: id,
                            deviceName: device_code,
                            filePath: dfuFilePath,
                        })
                            .then((res) => {})
                            .catch((err) => {
                                setUpdateVisible(false);
                            });
                    }
                })
                .catch((err) => {});
        }
    };
    const onModalHide = () => {
        if (deviceStore.dfuDevice?.id) {
            setUpdateVisible(true); // 先关闭连接Modal
            updateDevice();
        }
    };
    // 自动连接
    const autoStorageConnectDevice = async () => {
        if (userStore.autoConnectDeviceSn && deviceStore.device.connectedDeviceStatus == 0) {
            const hasAllPermissions = await checkAndRequestLocationAndBluetoothPermissions();
            if (hasAllPermissions) {
                Bleconnect.scan(5);
            }
        }
    };
    // 切换设备
    const [switchDeviceVisible, setSwitchDeviceVisible] = useState(false);
    const switchDevice = async () => {
        const permissionsGranted = await checkPermissions();
        if (!permissionsGranted) return;
        if (deviceStore.device.deviceStatus == 0) {
            Toast.show({ content: t('HomeScreen.t10'), layout: 'top' });
            return;
        }
        if (deviceStore.device.connectedDeviceStatus == 1) {
            deviceStore.disConnectble();
        }
        Bleconnect.scan(5);
        setSwitchDeviceVisible(true);
    };
    // 刷新上传数据
    const [refreshing, setRefreshing] = useState(false);
    const onRefresh = () => {
        if (device.connectedDeviceStatus == 0) return;
        setRefreshing(true);
        getDeviceDataHead((res) => {
            setRefreshing(false);
            Toast.show({ content: t('HomeScreen.t19') });
        });
    };
    useEffect(() => {
        if (deviceStore.dfuDevice?.id) {
            setConnectVisible(false); // 先关闭连接Modal
        }
    }, [deviceStore.dfuDevice?.id]);
    useEffect(() => {
        autoStorageConnectDevice();
    }, [userStore.autoConnectDeviceSn]);

    useEffect(() => {
        if (isFocused && !switchDeviceVisible) {
            const device = deviceStore.bleSearchbBindDevices.find(
                (item: any) => item.device_sn == userStore.autoConnectDeviceSn,
            );
            if (device) {
                setConnectVisible(true);
            }
        }
    }, [userStore.autoConnectDeviceSn, deviceStore.bleSearchbBindDevices]);
    return (
        <View style={styles.container}>
            <FocusAwareStatusBar translucent={true} barStyle={'light-content'} />
            <ImageBackground
                style={[styles.bg, { paddingTop: isIos() ? insets.top : insets.top + px2dp(32) }]}
                source={require('~/assets/login/bg4.png')}>
                <View style={[styles.row, styles.between]}>
                    <Pressable onPress={addDevice}>
                        <Icon name={'scan-outline'} size={px2dp(50)} color={'#fff'}></Icon>
                    </Pressable>
                    {/* <View style={styles.selectCalendar}>
                            <Pressable onPress={handlePrevDay}>
                                <Icon name={'chevron-back-outline'} size={px2dp(40)} color={'#fff'}></Icon>
                            </Pressable>
                            <Pressable style={styles.selectDay} onPress={() => setVisible(true)}>
                                <Text style={styles.day}>{getDisplayText()}</Text>
                            </Pressable>
                            <Pressable onPress={handleNextDay}>
                                <Icon name={'chevron-forward-outline'} size={px2dp(40)} color={'#fff'}></Icon>
                            </Pressable>
                        </View> */}
                    <View style={styles.row}>
                        {device.connectedDeviceStatus == 1 && userStore.userBindDeviceData.length > 1 && (
                            <Pressable style={{ marginRight: px2dp(32) }} onPress={switchDevice}>
                                <Icon name={'swap-horizontal-outline'} size={px2dp(40)} color={'#a4a4a4'}></Icon>
                            </Pressable>
                        )}
                        {device.connectedDeviceStatus == 1 && (
                            <Pressable onPress={connectDevice} style={[styles.row]}>
                                {yjhDevices.indexOf(device?.connectDevice?.device_code) == -1 && (
                                    <Text style={styles.eq}>{connectDeviceInfo?.eq}%</Text>
                                )}
                                <FastImage
                                    style={styles.device_image}
                                    source={{
                                        uri: device.connectDevice?.device_image,
                                        priority: FastImage.priority.normal,
                                    }}
                                    resizeMode={FastImage.resizeMode.contain}
                                />
                            </Pressable>
                        )}
                    </View>
                </View>
                <ScrollView
                    showsVerticalScrollIndicator={false}
                    contentContainerStyle={styles.contentStyle}
                    refreshControl={
                        <RefreshControl
                            refreshing={refreshing}
                            onRefresh={onRefresh}
                            tintColor="#fff" // ✅ iOS 加载圈颜色
                            colors={['#fff']}
                            title={t('HomeScreen.t18')} // 可选：显示文字
                            titleColor="#fff"
                        />
                    }>
                    {userStore.userBindDeviceData.length !== 0 ? (
                        <>
                            {device.connectedDeviceStatus == 0 ? (
                                <Pressable style={styles.card} onPress={connectDevice}>
                                    <View style={[styles.row, styles.between]}>
                                        <Text style={styles.t1}>{t('HomeScreen.t1')}</Text>
                                        <Icon name={'arrow-forward-outline'} size={px2dp(40)} color={'#a4a4a4'}></Icon>
                                    </View>
                                    <Text style={styles.t2}>{t('HomeScreen.t2')}</Text>
                                </Pressable>
                            ) : (
                                <View style={[styles.card, styles.row, styles.between]}>
                                    <Text style={[styles.t2, styles.successText]}>{t('HomeScreen.t15')}</Text>
                                    <Pressable style={styles.disConnect} onPress={() => deviceStore.disConnectble()}>
                                        <Text style={styles.disConnectText}>{t('HomeScreen.t16')}</Text>
                                    </Pressable>
                                </View>
                            )}
                        </>
                    ) : (
                        <Pressable style={styles.card} onPress={connectDevice}>
                            <View style={[styles.row, styles.between]}>
                                <Text style={styles.t1}>{t('HomeScreen.t12')}</Text>
                                <Icon name={'arrow-forward-outline'} size={px2dp(40)} color={'#a4a4a4'}></Icon>
                            </View>
                            <Text style={styles.t2}>{t('HomeScreen.t13')}</Text>
                        </Pressable>
                    )}
                    <Pressable
                        style={[styles.card, styles.row, { paddingVertical: 0 }]}
                        onPress={() => navigation.navigate('AiChat')}>
                        <Image source={require('~/assets/home/ai.png')} resizeMode="contain" style={styles.aiIcons} />
                        <Text style={[styles.t2, { marginTop: 0 }]}>{t('HomeScreen.t3')}</Text>
                    </Pressable>
                    {yjhDevices.indexOf(device?.connectDevice?.device_code) == -1 && (
                        <>
                            {device.connectedDeviceStatus == 1 && (
                                <View style={[styles.row, styles.between]}>
                                    <Pressable
                                        style={[styles.card, styles.cardWidth]}
                                        onPress={() => {
                                            if (userStore.userBindDeviceData.length == 0) {
                                                Toast.show({ content: t('HomeScreen.t17') });
                                                return;
                                            }
                                            navigation.navigate('Main', {
                                                screen: 'Health',
                                                params: {
                                                    id: 2,
                                                    title: t('HealthScreen.t1'),
                                                    icon: require('~/assets/home/heart.png'),
                                                },
                                            });
                                        }}>
                                        <View style={[styles.row, styles.between]}>
                                            <Text style={styles.card_title}>{t('HomeScreen.t4')}</Text>
                                            <Icon
                                                name={'chevron-forward-outline'}
                                                size={px2dp(40)}
                                                color={'#fff'}></Icon>
                                        </View>
                                        <View
                                            style={[
                                                styles.row,
                                                {
                                                    marginTop: px2dp(32),
                                                },
                                            ]}>
                                            <Image
                                                source={require('~/assets/home/data.png')}
                                                resizeMode="contain"
                                                style={styles.icons}
                                            />
                                            <Text style={styles.t3}>{t('HomeScreen.t5')}</Text>
                                        </View>
                                    </Pressable>
                                    <Pressable
                                        style={[styles.card, styles.cardWidth]}
                                        onPress={() => {
                                            if (device.connectedDeviceStatus == 0) {
                                                Toast.show({ content: t('HomeScreen.t20') });
                                                return;
                                            }
                                            const navigationParams = {
                                                type: 'ble',
                                                subDevice_sn: deviceInfo.device_sn,
                                                device_code: deviceInfo.device_code,
                                            };
                                            deviceStore.singRemoteInfo(navigationParams);
                                            navigation.navigate(
                                                offlineCourseDevices.indexOf(deviceInfo?.device_code) == -1
                                                    ? 'HealthManagement'
                                                    : 'HealthOfflineManagement',
                                                navigationParams,
                                            );
                                            // navigation.navigate('LaserCycle', {
                                            //     type: 'ble',
                                            //     subDevice_sn: deviceInfo?.device_sn,
                                            //     device_code: deviceInfo?.device_code,
                                            // });
                                        }}>
                                        <View style={[styles.row, styles.between]}>
                                            <Text style={styles.card_title}>{t('HomeScreen.t6')}</Text>
                                            <Icon
                                                name={'chevron-forward-outline'}
                                                size={px2dp(40)}
                                                color={'#fff'}></Icon>
                                        </View>
                                        <View
                                            style={[
                                                styles.row,
                                                {
                                                    marginTop: px2dp(32),
                                                },
                                            ]}>
                                            <Image
                                                source={require('~/assets/home/data.png')}
                                                resizeMode="contain"
                                                style={styles.icons}
                                            />
                                            <Text style={styles.t3}>{t('HomeScreen.t5')}</Text>
                                        </View>
                                    </Pressable>
                                </View>
                            )}
                            {/* 今日数据 */}
                            <DeviceData selectDate={currentDate} />
                        </>
                    )}
                </ScrollView>
            </ImageBackground>
            {/* 选择日历 */}
            <SelectCalendar
                currentDate={currentDate}
                visible={visible}
                onToggleVisible={() => setVisible(false)}
                onSelectDate={onSelectDate}
            />
            {/* 连接设备 */}
            <ConnectDeviceModal
                key={1}
                visible={ConnectVisible}
                onToggleVisible={() => setConnectVisible(false)}
                onModalHide={onModalHide}
            />
            <DfuProGressModal
                key={2}
                visible={updateVisible}
                upgradeSuccess={() => {
                    setUpdateVisible(false);
                    deviceStore.signDfuDevice({});
                    Toast.show({ content: t('HomeScreen.t14') });
                }}
                onToggleVisible={() => setUpdateVisible(false)}
            />
            <SelectDeviceModal visible={switchDeviceVisible} onToggleVisible={() => setSwitchDeviceVisible(false)} />
        </View>
    );
});

const styles = StyleSheet.create({
    row: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    center: {
        justifyContent: 'center',
    },
    between: {
        justifyContent: 'space-between',
    },
    container: {
        flex: 1,
    },
    contentStyle: {
        flexGrow: 1,
        paddingBottom: '30%',
    },
    bg: {
        flex: 1,
        resizeMode: 'contain',
        paddingHorizontal: px2dp(24),
        position: 'relative',
    },
    card: {
        borderWidth: 1,
        borderColor: 'rgba(255, 255, 255, 0.12)',
        padding: px2dp(24),
        marginTop: px2dp(48),
        borderRadius: px2dp(24),
        position: 'relative',
    },
    selectCalendar: {
        // backgroundColor: 'rgba(255, 255, 255, 0.12)',
        // flexDirection: 'row',
        // alignItems: 'center',
        // height: px2dp(80),
        // minWidth: px2dp(380),
        // borderRadius: px2dp(99999),
        // justifyContent: 'center',
        // paddingHorizontal: px2dp(12),
    },
    selectDay: {
        backgroundColor: 'rgba(216, 216, 216, 0.32)',
        height: px2dp(80),
        justifyContent: 'center',
        alignItems: 'center',
        minWidth: px2dp(186),
        paddingHorizontal: px2dp(12),
        borderRadius: px2dp(99999),
    },
    day: {
        color: '#fff',
        fontSize: scale(28),
    },
    t1: {
        color: '#ffff',
        fontSize: scale(30),
        fontWeight: 'bold',
    },
    t2: {
        color: '#a4a4a4',
        fontSize: scale(26),
        marginTop: px2dp(24),
        lineHeight: px2dp(40),
    },
    aiIcons: {
        width: px2dp(96),
        height: px2dp(110),
    },
    cardWidth: {
        width: (width - px2dp(96)) / 2,
    },
    card_title: {
        color: '#fff',
    },
    icons: {
        width: px2dp(40),
        height: px2dp(40),
        marginRight: px2dp(24),
    },
    t3: {
        color: '#a4a4a4',
        fontSize: scale(26),
    },
    smaile: {
        width: px2dp(64),
        height: px2dp(64),
    },
    device_text: {
        color: '#fff',
        fontSize: scale(28),
    },
    device_image: {
        width: px2dp(60),
        height: px2dp(60),
    },
    eq: {
        color: '#C4C4C4',
        fontSize: scale(28),
        fontWeight: 'bold',
    },
    disConnect: {
        backgroundColor: 'rgba(255, 255, 255, 0.12)',
        flexDirection: 'row',
        alignItems: 'center',
        height: px2dp(80),
        borderRadius: px2dp(99999),
        justifyContent: 'center',
        paddingHorizontal: px2dp(12),
    },
    successText: {
        width: px2dp(500),
        color: '#1DCE87',
    },
    disConnectText: {
        color: '#fff',
        fontSize: scale(26),
    },
});
